package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishUserController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     *
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        DishDTO dishDTO = new DishDTO();
        dishDTO.setCategoryId(categoryId);
        dishDTO.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
        //1.先查询缓存
        String CACHE_DISH_KEY = "DISH_" + categoryId;
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(CACHE_DISH_KEY);
        //2.如果缓存存在直接返回
        if (list != null){
            return Result.success(list);
        }
        //3.如果缓存存在才查询数据库,并且将数据加到缓存中
        //根据菜品id查询菜品和对应口味
        list = dishService.listWithFlavor(dishDTO);
        redisTemplate.opsForValue().set(CACHE_DISH_KEY,list);
        return Result.success(list);
    }
}